package com.example.demo.controller;

import com.example.demo.entity.SysRole;
import com.example.demo.entity.SysUser;
import com.example.demo.repository.SysRoleRepository;
import com.example.demo.repository.SysUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * Copyright(C), 2020-2021, AmbroseCdMeng
 * FileName:    SysUserController
 * Author:      AmbroseCdMeng
 * Date:        2021/3/5 10:41
 * Description: 用户管理控制器
 * History:
 * <author>     <time>      <version>       <desc>
 * 作者姓名     修改时间        版本号           描述
 */
@Controller
@RequestMapping("admin")
public class SysUserController {
    @Autowired
    private SysUserRepository sysUserRepository;

    @Autowired
    private SysRoleRepository sysRoleRepository;

    //@PreAuthorize("hasRole('ROLE_admin')")
    @RequestMapping("/user/add")
    public String toAddUser(Model model){
        Iterable<SysRole> adminRoles = sysRoleRepository.findAll();
        model.addAttribute("adminRoles", adminRoles);
        return "admin/user/add";
    }

    //@RequestMapping("/user/add")
    @PostMapping("/user")
    public String addUser(String name, String password, String role){
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodePassword = encoder.encode(password);
        SysUser user = new SysUser(name, encodePassword);
        List<SysRole> roles = new ArrayList<>();
        SysRole r1 = sysRoleRepository.findByRole(role);
        roles.add(r1);
        user.setRoles(roles);
        sysUserRepository.save(user);
        return "redirect:/admin/";
    }
}
